import React, { useState, useEffect, type ReactNode } from 'react';
import { message } from 'antd';
import type { UserInfo } from '../api/dto/user';
import { userApi } from '../api/services/user/user';
import { UserContext } from './UserContext';

interface UserProviderProps {
  children: ReactNode;
}

export const UserProvider: React.FC<UserProviderProps> = ({ children }) => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);

  // 获取最新用户信息的方法
  const refreshUserInfo = async (userId: number) => {
    try {
      const userInfoResponse = await userApi.getUserInfoById(userId);

      if (userInfoResponse.code === 0 || userInfoResponse.code === 200) {
        const fullUserInfo = {
          id: userInfoResponse.data?.id || userId,
          username: userInfoResponse.data?.username || '',
          name: userInfoResponse.data?.name || '',
          avatar: userInfoResponse.data?.avatar || null,
          profileId: userInfoResponse.data?.profileId || '',
          email: userInfoResponse.data?.email,
          systemRole: userInfoResponse.data?.systemRole,
          signature: userInfoResponse.data?.signature
        };

        // 更新 localStorage 和状态
        localStorage.setItem("userInfo", JSON.stringify(fullUserInfo));
        setUserInfo(fullUserInfo);
        console.log('用户信息已刷新:', fullUserInfo);
      } else {
        console.error('获取用户信息失败:', userInfoResponse.message);
      }
    } catch (error) {
      console.error("刷新用户信息失败:", error);
    }
  };

  useEffect(() => {
    const token = localStorage.getItem('token');
    const storedUserInfo = localStorage.getItem('userInfo');

    if (token && storedUserInfo) {
      setIsLoggedIn(true);
      try {
        const parsedUserInfo = JSON.parse(storedUserInfo);
        setUserInfo(parsedUserInfo);

        // 页面刷新时自动获取最新用户信息
        if (parsedUserInfo.id) {
          refreshUserInfo(parsedUserInfo.id);
        }
      } catch (error) {
        console.error('Failed to parse user info:', error);
      }
    }
  }, []);

  const login = (userInfo: UserInfo) => {
    setIsLoggedIn(true);
    setUserInfo(userInfo);
  };

  const logout = async () => {
    try {
      // 调用后端登出API
      const response = await userApi.logout();
      
      if (response.code === 0 || response.code === 200) {
        message.success('退出登录成功');
      } else {
        message.error(response.message || '退出登录失败');
      }
    } catch (error) {
      console.error('登出请求失败:', error);
      message.error('退出登录失败，请稍后再试');
    } finally {
      // 无论后端请求是否成功，都清除本地状态
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      setIsLoggedIn(false);
      setUserInfo(null);
    }
  };

  return (
    <UserContext.Provider value={{ isLoggedIn, userInfo, login, logout }}>
      {children}
    </UserContext.Provider>
  );
}; 